package com.hulman.oms.service;

import com.hulman.oms.bean.Result;
import com.hulman.oms.bean.QuarterReport;
import com.hulman.oms.bean.User;
import com.hulman.oms.dao.QuarterReportDao;
import com.hulman.oms.exception.IoTException;
import com.hulman.oms.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.temporal.TemporalAdjusters;
import java.util.*;

/**
 * @Author: maxwellens
 */
@Service
public class QuarterReportService
{
    @Value("${file-home}")
    private String fileHome;
    @Autowired
    private QuarterReportDao quarterReportDao;
    @Autowired
    private OnlyOfficeService onlyOfficeService;

    public List<QuarterReport> findQuarterReports(Map<String, Object> map)
    {
        return quarterReportDao.findQuarterReports(map);
    }

    public Integer findQuarterReportsCount(Map<String, Object> map)
    {
        return quarterReportDao.findQuarterReportsCount(map);
    }

    public Result findQuarterReportsResult(Map<String, Object> map)
    {
        Integer page = (Integer) map.get("page");
        Integer limit = (Integer) map.get("limit");
        if (page != null && limit != null)
        {
            map.put("start", (page - 1) * limit);
            map.put("length", limit);
        }
        int count = quarterReportDao.findQuarterReportsCount(map);
        List<QuarterReport> data = quarterReportDao.findQuarterReports(map);
        return new Result(data, count);
    }

    public QuarterReport findQuarterReportById(Integer id)
    {
        return quarterReportDao.findQuarterReportById(id);
    }

    public void saveQuarterReport(QuarterReport quarterReport)
    {
        if (quarterReport.getId() != null && quarterReport.getId() != 0)
        {
            quarterReportDao.updateQuarterReport(quarterReport);
        } else
        {
            quarterReportDao.insertQuarterReport(quarterReport);
        }
    }

    public void deleteQuarterReportById(Integer id)
    {
        quarterReportDao.deleteQuarterReportById(id);
    }

    public void deleteQuarterReports(int[] ids)
    {
        quarterReportDao.deleteQuarterReports(ids);
    }

    /**
     * 检查工作报告是否已生成
     *
     * @param quarterReport
     */
    public void checkQuarterReport(QuarterReport quarterReport)
    {
        Map<String, Object> map = new HashMap<>();
        map.put("year", quarterReport.getYear());
        map.put("quarter", quarterReport.getQuarter());
        Integer count = quarterReportDao.findQuarterReportsCount(map);
        if (count > 0)
        {
            throw new IoTException("该季度工作报告已生成");
        }
    }

    public void create(QuarterReport quarterReport) throws IOException
    {
        checkQuarterReport(quarterReport);
        User user = SubjectUtil.getUser();
        quarterReport.setCreateById(user.getId());
        quarterReport.setCreateByName(user.getName());
        int year = quarterReport.getYear();
        int quarter = quarterReport.getQuarter();
        LocalDate firstDay = LocalDate.of(year, (quarter - 1) * 3 + 1, 1);
        LocalDate lastDay = LocalDate.of(year, quarter * 3, 1).with(TemporalAdjusters.lastDayOfMonth());
        Date startDate = Date.from(firstDay.atStartOfDay(ZoneId.systemDefault()).toInstant());
        Date endDate = Date.from(lastDay.atStartOfDay(ZoneId.systemDefault()).toInstant());
        quarterReport.setStartDate(startDate);
        quarterReport.setEndDate(endDate);
        quarterReport.setState(0);
        //模板生成报告
        if (quarterReport.getSource() == 1)
        {
            Map<String, Object> map = new HashMap<>();
            map.put("today", DateUtil.toChineseDate(DateUtil.now()));
            map.put("year", year);
            map.put("quarter", quarter);
            map.put("startDate", DateUtil.toChineseDate(startDate));
            map.put("endDate", DateUtil.toChineseDate(endDate));
            InputStream inputStream = Thread.currentThread().getContextClassLoader()
                    .getResourceAsStream("template/quarter-report.docx");
            String fileId = StringUtil.uuid() + ".docx";
            Path filePath = Paths.get(fileHome, fileId);
            OutputStream outputStream = Files.newOutputStream(filePath);
            DocUtil.export(inputStream, outputStream, map);
            quarterReport.setFileId(fileId);
        }
        quarterReportDao.insertQuarterReport(quarterReport);
        String fileName = quarterReport.getReportCycle() + "养护季报." + FileUtil.parseExtName(quarterReport.getFileId());
        onlyOfficeService.create(quarterReport.getFileId(), fileName);
    }

    public void submit(Integer id)
    {
        QuarterReport quarterReport = quarterReportDao.findQuarterReportById(id);
        quarterReport.setState(1);
        quarterReport.setEditDate(new Date());
        quarterReportDao.updateQuarterReport(quarterReport);
    }

}
